package com.atguigu.gmall.user.filter;

import com.atguigu.gmall.common.util.GmallThreadLocalUtils;
import com.atguigu.gmall.user.util.TokenUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/***
 * 用户微服务自定义过滤器
 */
@WebFilter(filterName = "userFilter",urlPatterns = "/*")
public class UserFilter extends GenericFilter {

    /**
     * 过滤逻辑
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //强制类型转换
        HttpServletRequest request = (HttpServletRequest)servletRequest;

        //去出请求头,获取请求头中的令牌
        String token = request.getHeader("Authorization").replace("bearer ", "");

        //并解析
        Map<String, String> map = TokenUtil.dcodeToken(token);
        String username = map.get("username");

        //将用户名存入本地线程中
        GmallThreadLocalUtils.set(username);

        //放行
        filterChain.doFilter(request,servletResponse);
    }
}
